import Vue from 'vue'
import Vuex from 'vuex'
import {getRequest} from "../utils/api";
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

Vue.use(Vuex);


const store = new Vuex.Store({
	state:{
		routes:[],
        sessions: {},
        admins:[],
        currentAdmin: JSON.parse(window.sessionStorage.getItem('user')),
        currentSession: null,
        filterKey:'',
        stomp: null,
        isDot: {}
	},

	mutations:{
		initRoutaes(state,data){
			state.routes = data;
		}
	},
	actions:{
		connect(context){
            context.state.stomp = Stomp.over(new SockJS('/ws/ep'));
            let token = window.sessionStorage.getItem('tokenStr')
            context.state.stomp.connect({'Auth-Token':token}
                ,success => {
                    context.state.stomp.subscribe('/user/queue/chat',msg => {
                        // console.log(msg.body)
                        let receiveMsg = JSON.parse(msg.body)
                        if (!context.state.currentSession || receiveMsg.from !== context.state.currentSession.username){
                            Notification.info({
                                title: '【'+receiveMsg.nickName+'】发来一条消息！',
                                message: receiveMsg.contentlength > 10 ? receiveMsg.content.substr(0,10) : receiveMsg.content,
                                position: 'bottom-right'
                            })
                            Vue.set(context.state.isDot
                                , context.state.currentAdmin.username+'#'+receiveMsg.from,
                                true)
                        }
                        receiveMsg.notSelf = true
                        receiveMsg.to = receiveMsg.from
                        context.commit('addMessage',receiveMsg)
                    })
                },error => {

                })
        },
	}
})
export default store;